import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { InviteRelation } from './assets/inviteRelation.entity';
import { Brackets, Repository } from 'typeorm';
import { util_Db_PageList } from '@/common/util/db';
import { InviteRelation_InviteListFind_Dto } from './assets/inviteRelation.dto';
import { Constant_Enum_Enum_Order_PayStatus } from '@/common/constants/enum';
import { Order } from '../order/assets/order.entity';

@Injectable()
export class InviteRelation_Service {
  constructor(
    @InjectRepository(InviteRelation)
    private inviteRelation_Repository: Repository<InviteRelation>,
  ) {}

  async inviteRelation_InviteListFindByPage(data: InviteRelation_InviteListFind_Dto) {
    return await util_Db_PageList<InviteRelation>({
      queryBuilder: this.inviteRelation_Repository
        .createQueryBuilder('inviteRelation')
        .leftJoin('inviteRelation.inviter', 'inviter')
        .leftJoin('inviteRelation.invitee', 'invitee')
        .select(['invitee.createTime AS createTime', 'invitee.userName AS userName', 'invitee.id AS id'])
        .andWhere('inviteRelation.createTime IS NOT NUll')
        .addSelect((subQuery) => {
          const subQb = subQuery
            .select('COUNT(order.id)', 'orderCount')
            .from(Order, 'order')
            .where('order.userClient = inviteRelation.inviteeId')
            .andWhere(
              new Brackets((qb) => {
                qb.where('order.status = :payStatus', {
                  payStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Pay,
                }).orWhere('order.status = :refundStatus', {
                  refundStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund,
                });
              }),
            );
          if (data.startTime) {
            subQb.andWhere('inviteRelation.createTime >= :startTime', { startTime: data.startTime });
          }
          if (data.endTime) {
            subQb.andWhere('inviteRelation.createTime <= :endTime', { endTime: data.endTime });
          }
          return subQb;
        }, 'orderCount'),
      query: {
        'invitee.id': data.inviteeId,
        'invitee.userName': data.inviterName,
        'inviter.id': data.inviterId,
        size: data.size,
        page: data.page,
      },
      getQuery: true,
      isRaw: true,
    });
  }
}
